#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>  // 新增必要头文件

#define BUFFER_SIZE 1024

void reverse(char *str) {
    if (!str) return;
    int len = strlen(str);
    for (int i = 0; i < len/2; i++) {
        char temp = str[i];
        str[i] = str[len-i-1];
        str[len-i-1] = temp;
    }
}

int main() {
    int pipefd[2];
    pid_t pid;
    char parent_msg[] = "Hello Pipe!";
    char child_buf[BUFFER_SIZE];
    char parent_buf[BUFFER_SIZE];

    if (pipe(pipefd) == -1) {
        perror("pipe failed");
        exit(EXIT_FAILURE);
    }

    pid = fork();
    if (pid < 0) {
        perror("fork failed");
        exit(EXIT_FAILURE);
    }

    if (pid == 0) {     // 子进程
        close(pipefd[1]);

        ssize_t count = read(pipefd[0], child_buf, BUFFER_SIZE);
        child_buf[count] = '\0';
        printf("Child received: %s\n", child_buf);

        reverse(child_buf);
        
        write(pipefd[1], child_buf, strlen(child_buf));
        close(pipefd[0]);
        exit(EXIT_SUCCESS);

    } else {            // 父进程
        close(pipefd[0]); 

        printf("Parent sending: %s\n", parent_msg);
        write(pipefd[1], parent_msg, strlen(parent_msg)+1);

        sleep(1);  
        
        ssize_t count = read(pipefd[0], parent_buf, BUFFER_SIZE);
        parent_buf[count] = '\0';
        printf("Parent received: %s\n", parent_buf);

        close(pipefd[1]);
        wait(NULL);  // 现在已正确定义
    }

    return 0;
}
